package cn.com.dhc.danlu.yijifu;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.yiji.www.paymentcenter.YijiPayPlugin;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.api.DanluApi;
import cn.com.dhc.danlu.dlware.global.DanluApplication;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.util.CommonConst;
import cn.com.dhc.danlu.util.PreferenceUtils;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.dialog.ViewDialog;
import cn.com.hd.mall.web.webservices.entity.BaseResponse;
import cn.com.hd.mall.web.webservices.entity.request.order.CreateQftSDKPaymentOrderRequest;
import cn.com.hd.mall.web.webservices.entity.request.order.GetQftUserInfoRequest;
import cn.com.hd.mall.web.webservices.entity.request.order.GetYijipayConfigRequest;
import cn.com.hd.mall.web.webservices.entity.request.order.PaymentResultNotifyRequest;
import cn.com.hd.mall.web.webservices.entity.response.order.GetQftUserInfoResponse;
import cn.com.hd.mall.web.webservices.entity.response.order.GetTradeNoResponse;
import cn.com.hd.mall.web.webservices.entity.response.order.GetYijipayConfigResponse;

import static android.content.ContentValues.TAG;
import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;
import static cn.com.dhc.danlu.util.CommonConst.PaymentConst.PAYMENT_BUYER_INFO_FAIL_3;
import static cn.com.dhc.danlu.util.CommonConst.WebservicesConst.LOGIN_RESPONSE_SUCCESS_0;

/**
 * @author: 吴海洋
 * @version: 1.0.0
 * @since: 2016-11-15 15:34
 * @mail: wuhaiyang@danlu.com
 * @desc: 封装易极付请求相关
 * @fixme : flatmap
 */
public class YjfPayEngine {
    /**
     * 易极付开户识别码
     */
    public static final int YIJIFU_REGISTER_CODE = 2;
    /**
     * 易极付支付识别码
     */
    public static final int YIJIFU_PAYYMENT_CODE = 11;
    /**
     * 支付状态通知服务器异步识别码
     */
    private static final int PAYMENT_STATE_RESULT_CODE = 2;
    /**
     * 支付状态通知服务器时间间隔5秒
     */
    private static final int PAYMENT_STATE_INTERVAL_5 = 5000;
    /**
     * 支付状态通知服务器时间间隔10秒
     */
    private static final int PAYMENT_STATE_INTERVAL_10 = 10000;

    /**
     * 丹露交易号
     */
    private String danluPaymentNo;
    /**
     * 易极付用户ID
     */
    private String yijiUserId;

    /**
     * 支付状态通知服务器次数
     */
    private int notifyTimes = 3;
    /**
     * 支付回调结果
     */
    private int payResultCode = -1;

    private Activity mContext;
    /**
     * 支付回调接口响应实例
     */
    private IPayResultCallback ipayResultCallback = null;
    /**
     * 支付通知机制实现
     */
    final Handler notifyHandler = new Handler () {

        public void handleMessage (Message msg) {
            switch (msg.what) {
                // 获取handler支付状态标识
                case PAYMENT_STATE_RESULT_CODE:
                    if (msg.obj != null) {
                        int code = (Integer) msg.obj;
                        if (notifyTimes > 0) {
                            notifyTimes--;
                            notifyPayResult (code);
                        } else {
                            //                            Log.i (TAG, "已经请求三次服务器");
                            // 移除通知服务器标识
                            notifyHandler.removeMessages (PAYMENT_STATE_RESULT_CODE);
                        }

                    } else {
                        //                        Log.i (TAG, "交易号传输丢失");
                        // 移除通知服务器标识
                        notifyHandler.removeMessages (PAYMENT_STATE_RESULT_CODE);
                    }
                    break;
            }

            super.handleMessage (msg);
        }
    };
    private boolean isBindCard = false;
    private DanluApi api = agent.getApi ();

    public YjfPayEngine (Activity context, IPayResultCallback callback, boolean isBindCard) {
        mContext = context;
        this.ipayResultCallback = callback;
        this.isBindCard = isBindCard;
    }

    public void payAction (String payNo) {
        danluPaymentNo = payNo;
        getYjfConfig ();
        // flatmap
    }

    /**
     * 获取易极付常量
     */
    public void getYjfConfig () {
        GetYijipayConfigRequest getYijipayConfigRequest = new GetYijipayConfigRequest ();
        getYijipayConfigRequest.setToken (agent.getToken ());
        //add by llq
        api.getYifConfigConstants (getYijipayConfigRequest)
                .compose (OperatorUtils.<GetYijipayConfigResponse>defaultSchedulers ())
                .subscribe (new GeneralBusinessObserver<GetYijipayConfigResponse> (mContext, R.string.loading_common_msg) {
                    @Override
                    protected void onSuccess (GetYijipayConfigResponse getYijipayConfigResponse) {
                        String partnerId = getYijipayConfigResponse.getPartnerId ();
                        String key = getYijipayConfigResponse.getKey ();
                        if (!TextUtils.isEmpty (partnerId) && !TextUtils.isEmpty (key)) {
                            YijiPayPlugin.setPartnerId (partnerId);
                            YijiPayPlugin.setSecretKey (key);
                            // 获取商户开户ID
                            getYjfUserInfo ();
                        }
                    }

                    @Override
                    protected void onAlertTips (String displayMessage) {
                        if (ipayResultCallback != null) {
                            ipayResultCallback.payError (R.string.yjf_pay_fail);
                        }
                    }
                });
    }

    /**
     * 获取买家易极付账户信息
     */
    private void getYjfUserInfo () {
        GetQftUserInfoRequest getQftUserInfoRequest = new GetQftUserInfoRequest ();
        getQftUserInfoRequest.setToken (agent.getToken ());
        // 由于登陆接口已经将userId 和CompanyId 独立区分开了
        getQftUserInfoRequest.setUserId (agent.getLoginUser ().getCompanyId ());
        getQftUserInfoRequest.setUserName (new PreferenceUtils (mContext).getFullName ());
        api.getYifUserInfo (getQftUserInfoRequest)
                .compose (OperatorUtils.<GetQftUserInfoResponse>defaultSchedulers ())
                .subscribe (new GeneralBusinessObserver<GetQftUserInfoResponse> () {
                    @Override
                    public void onNext (GetQftUserInfoResponse res) {
                        if (res.getErrorCode ().equals (PAYMENT_BUYER_INFO_FAIL_3)) {
                            dismissDialog ();
                            YJBuyerRigsterDialog ();
                            return;
                        }
                        if (res.getSuccess ().equals (LOGIN_RESPONSE_SUCCESS_0)) {
                            onSuccess (res);
                        } else {
                            onAlertTips (null);
                        }
                    }

                    @Override
                    protected void onSuccess (GetQftUserInfoResponse res) {
                        // 获取买家易极付账户信息--成功
                        yijiUserId = res.getYijiUserId ();
                        if (isBindCard) {
                            try {
                                YijiPayPlugin.startBindCard (mContext, yijiUserId);
                            } catch (Exception e) {
                                e.printStackTrace ();
                            }
                        } else {
                            obtainDealInfo ();
                        }
                    }

                    @Override
                    protected void onAlertTips (String displayMessage) {
                        if (ipayResultCallback != null) {
                            ipayResultCallback.payError (R.string.yjf_get_buyerInfo_fail);
                        }
                    }
                });
    }

    /**
     * 获取易极付交易号
     */
    private void obtainDealInfo () {
        CreateQftSDKPaymentOrderRequest createQftSDKPaymentOrderRequest = new CreateQftSDKPaymentOrderRequest ();
        createQftSDKPaymentOrderRequest.setToken (agent.getToken ());
        createQftSDKPaymentOrderRequest.setPayNo (danluPaymentNo);
        String companyId = agent.getLoginUser ().getCompanyId ();
        createQftSDKPaymentOrderRequest.setUserId (companyId);
        api.createDealNumber (createQftSDKPaymentOrderRequest)
                .compose (OperatorUtils.<GetTradeNoResponse>defaultSchedulers ())
                .subscribe (new GeneralBusinessObserver<GetTradeNoResponse> (mContext, R.string.tips_getting_yjf_trade_num) {
                    @Override
                    protected void onSuccess (GetTradeNoResponse getTradeNoResponse) {
                        // 获取支付号--成功
                        String tradeNo = getTradeNoResponse.getTradeNo ();
                        try {
                            YijiPayPlugin.startPay (mContext, tradeNo, YIJIFU_PAYYMENT_CODE, yijiUserId);
                        } catch (Exception e) {
                            e.printStackTrace ();
                        }
                    }

                    @Override
                    protected String parseBussinessException (String code) {
                        if (code.equals (CommonConst.PaymentConst.PAYMENT_NO_VER_CODE_SUCCESS_1)) {
                            // 获取支付号--失败
                            if (ipayResultCallback != null) {
                                ipayResultCallback.payError (R.string.yjf_get_tradeNo_fail);
                            }
                        } else if (code.equals (CommonConst.PaymentConst.PAYMENT_NO_VER_CODE_SUCCESS_2)) {
                            // 获取支付号--未开户
                            if (ipayResultCallback != null) {
                                ipayResultCallback.payError (R.string.yjf_get_tradeNo_fail_account);
                            }
                        }
                        return DanluApplication.get ().getString (R.string.yjf_get_tradeNo_fail_account);
                    }

                    @Override
                    protected void onAlertTips (String displayMessage) {
                        if (ipayResultCallback != null) {
                            ipayResultCallback.payError (R.string.yjf_get_tradeNo_fail);
                        }
                        ToastUtil.getInstance ().show (displayMessage);
                    }
                });
    }

    /**
     * 向服务器提供支付状态
     */
    public void notifyPayResult (int code) {
        String requestCode;
        PaymentResultNotifyRequest paymentResultNotifyRequest = new PaymentResultNotifyRequest ();
        paymentResultNotifyRequest.setToken (agent.getToken ());
        paymentResultNotifyRequest.setPayNo (danluPaymentNo);
        String userid = agent.getLoginUser ().getCompanyId ();
        paymentResultNotifyRequest.setUserId (userid);
        if (YijiPayPlugin.RESULT_PAY_CANCEL == code) {
            requestCode = CommonConst.PaymentConst.PAYMENT_ORDER_NOPAY;
            paymentResultNotifyRequest.setPayStatus (requestCode);
            // 回调交易状态接口
            callNotifyServerComplete (paymentResultNotifyRequest);
            if (ipayResultCallback != null) {
                ipayResultCallback.noPay ();
            }
        } else if (YijiPayPlugin.RESULT_PAYING == code) {
            requestCode = CommonConst.PaymentConst.PAYMENT_ORDER_PAYING;
            paymentResultNotifyRequest.setPayStatus (requestCode);
            // 回调交易状态接口
            callNotifyServerComplete (paymentResultNotifyRequest);
            if (ipayResultCallback != null) {
                ipayResultCallback.paying ();
            }
        } else if (YijiPayPlugin.RESULT_PAY_FAILURE == code || YijiPayPlugin.RESULT_PAY_EXCEPTION == code) {
            requestCode = CommonConst.PaymentConst.PAYMENT_ORDER_PAY_FAILURE;
            paymentResultNotifyRequest.setPayStatus (requestCode);
            // 回调交易状态接口
            callNotifyServerComplete (paymentResultNotifyRequest);
            if (ipayResultCallback != null) {
                ipayResultCallback.payFail ();
            }
        } else if (YijiPayPlugin.RESULT_PAY_SUCCESS == code) {
            requestCode = CommonConst.PaymentConst.PAYMENT_ORDER_PAYED;
            paymentResultNotifyRequest.setPayStatus (requestCode);
            // 回调交易状态接口
            callNotifyServerComplete (paymentResultNotifyRequest);
            /*if (ipayResultCallback != null) {
                ipayResultCallback.paySuccess ();
            }*/
        }
    }

    /**
     * 通知易极付交易结果
     *
     * @param request
     *         请求体
     */
    private void callNotifyServerComplete (final PaymentResultNotifyRequest request) {
        agent.getApi ().paymentResultNotify (request)
                .compose (OperatorUtils.defaultSchedulers ())
                .subscribe (new GeneralBusinessObserver<BaseResponse> () {
                    @Override
                    protected void onSuccess (BaseResponse baseResponse) {
                        String status = request.getPayStatus ();
                        payFinish ();
                    }

                    @Override
                    protected void onAlertTips (String displayMessage) {
                        notifyStatusMechanism (payResultCode);
                    }
                });
    }

    /**
     * 支付流程完毕
     */
    private void payFinish () {
        // 移除通知服务器标识
        notifyHandler.removeMessages (PAYMENT_STATE_RESULT_CODE);
        if (ipayResultCallback != null) {
            ipayResultCallback.paySuccess ();
        }
    }

    /**
     * App将支付结果回调给Sevenr，如果回调成功则结束，如果回调不成功，按照间隔5秒和10秒进行第二次和第三次回调，如果均不成功，结束
     */
    private void notifyStatusMechanism (int code) {
        if (notifyTimes == 2) {
            // 延时5s再次请求服务器
            Message message = notifyHandler.obtainMessage (PAYMENT_STATE_RESULT_CODE);
            message.obj = code;
            notifyHandler.sendMessageDelayed (message, PAYMENT_STATE_INTERVAL_5);
        } else if (notifyTimes == 1) {
            // 延时10s再次请求服务器
            Message message = notifyHandler.obtainMessage (PAYMENT_STATE_RESULT_CODE);
            message.obj = code;
            notifyHandler.sendMessageDelayed (message, PAYMENT_STATE_INTERVAL_10);
        } else {
            Log.i (TAG, "已经请求三次服务器");
            payFinish ();
        }
    }

    /**
     * 收到支付结果后，进行后续处理
     */
    public void handlerPayResult (int requestCode, int resultCode, Intent data) {
        if (requestCode == YIJIFU_PAYYMENT_CODE) {
            notifyTimes = 3;
            payResultCode = resultCode;
            Message message = notifyHandler.obtainMessage (PAYMENT_STATE_RESULT_CODE);
            message.obj = payResultCode;
            notifyHandler.sendMessage (message);
        } else if (requestCode == YIJIFU_REGISTER_CODE) {
            //            getYjfConfig ();
            //            if (!TextUtils.isEmpty (danluPaymentNo))
            //                payAction (danluPaymentNo);
        }
    }

    /**
     * 支付账户开户提示对话框
     */
    private void YJBuyerRigsterDialog () {
//        PromptManager.closeDialog ();
        ViewDialog.Builder builder = new ViewDialog.Builder (mContext);

        // 设置标题
        builder.setTitle (R.string.prompt_label);
        // 设置信息
        builder.setMessage (mContext.getResources ().getString (R.string.yjf_buyer_register_fail_prompt));
        // 设置Positive按钮点击监听
        builder.setPositiveButton (R.string.btn_ok, new DialogInterface.OnClickListener () {

            @Override
            public void onClick (DialogInterface dialog, int which) {
                // 对话框关闭
                Intent intent = new Intent ();
                intent.setClass (mContext, YJBuyerRegisterActivity.class);
                mContext.startActivityForResult (intent, YIJIFU_REGISTER_CODE);
                dialog.dismiss ();
            }
        });
        // 创建对话框并显示
        builder.create ().show ();
    }


}
